//
//  APIManager.m
//  RWUIControls
//
//  Created by shenchengcai on 15/3/3.
//  Copyright (c) 2015年 QM. All rights reserved.
//

#import "APIManager.h"
#import "TMDiskCache.h"
//#import "AFHTTPClient.h"
//#import "AFJSONRequestOperation.h"
#import "AFNetworking.h"
#import "JoDEs.h"
//#import "NSString+JsonString.h"
#import "JsonString.h"
#import "Soap.h"

NSString *ManagerIPString = @"192.168.102.11";
NSString *LoginIPStirng = @"192.168.102.11";//@"182.92.182.60:8011";
//设置加密解密key
NSString *EncryKeyString = @"20140401";
//设置加密解密key－小明
NSString *EncryKeyString2 = @"q0m3sd8l";

@interface APIManager()

@property(nonatomic,retain)AFHTTPRequestOperationManager *client;

@end

@implementation APIManager

+(void)sheZhiLoginIP:(NSString *)IPString{
    LoginIPStirng =IPString;
}

+(void)sheZhiIP:(NSString *)IPString{
    ManagerIPString =IPString;
}

+(void)sheZhiKey:(NSString *)keyString{
    EncryKeyString = keyString;
}
//设置加密解密key－小明
+(void)sheZhiKey2:(NSString *)keyString{
    EncryKeyString2 = keyString;
}

//获取加密解密key
+(NSString *)getKeyString {
    return EncryKeyString ? EncryKeyString : @"20140401";
}

//获取加密解密key－小明
+(NSString *)getKeyString2 {
    return EncryKeyString2 ? EncryKeyString2 : @"q0m3sd8l";
}


//共享实例方法
+ (APIManager *)sharedInstance {
    
    AFHTTPRequestOperationManager *instance = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@/", ManagerIPString]]];
    if (!instance) {
        return nil;
    }
    
//    [instance registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    
    // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
//    [instance setDefaultHeader:@"Accept" value:@"application/x-www-form-urlencoded"];
    
    APIManager *apiManager = [[APIManager alloc] init];
    apiManager.client = instance;
    return apiManager;
}

//初始化方法-登录URL
+ (APIManager *)loginInstance {
    
    AFHTTPRequestOperationManager *instance = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@/", LoginIPStirng]]];
    if (!instance) {
        return nil;
    }
    
//    [instance registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    
    // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
//    [instance setDefaultHeader:@"Accept" value:@"application/x-www-form-urlencoded"];
    
    APIManager *apiManager = [[APIManager alloc] init];
    apiManager.client = instance;
    return apiManager;
}

//代理方法。在释放内存的代理方法中控制共享实例不能dealloc
- (void)dealloc {
    //共享实例不能dealloc
    //    abort();
}

#pragma mark - CACHE
//缓存方法。返回key对应的content。key键值
- (id) cachedContent:(NSString *)key {
    return [[TMDiskCache sharedCache] objectForKey:key];
}
//缓存方法。设置键值对。key键值；content内容
- (void) setCachedContent:(id)content withKey:(NSString *)key {
    [[TMDiskCache sharedCache] setObject:content forKey:key];
}

#pragma mark - 请求数据方法
//请求方法。向接口请求数据，并接收返回值。path方法路径；parameters参数；success请求成功时处理方法；failure请求失败时处理方法
- (void)getPath:(NSString *)path

     parameters:(NSDictionary *)parameters
        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    
//    NSURLRequest *request =
    [self.client GET:path
          parameters:parameters
             success:success
             failure:failure];//requestWithMethod:@"GET" path:path parameters:parameters];
//    AFHTTPRequestOperation *operation = [self.client HTTPRequestOperationWithRequest:request success:success failure:failure];
//    [self.client enqueueHTTPRequestOperation:operation];
}

//请求方法。向接口请求数据，并接收返回值。path方法路径；parameters参数；success请求成功时处理方法；failure请求失败时处理方法
- (void)postPath:(NSString *)path
      parameters:(NSDictionary *)parameters
         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    
//    NSURLRequest *request = [self.client requestWithMethod:@"POST" path:path parameters:parameters];
    [self.client POST:path
           parameters:parameters
              success:success
              failure:failure];
//    AFHTTPRequestOperation *operation = [self.client HTTPRequestOperationWithRequest:request success:success failure:failure];
//    [self.client enqueueHTTPRequestOperation:operation];
}



//请求方法。向接口请求数据，并接收返回值。path方法路径；parameters参数；dataDic需上传的数据；dataType数据类型；success请求成功时处理方法；failure请求失败时处理方法
- (void)postPath:(NSString *)path
      parameters:(NSDictionary *)parameters
         dataDic:(NSDictionary *)dataDic
        dataType:(NSString *)dataType
         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    //上传请求POST
//    NSMutableURLRequest *request = [self.client multipartFormRequestWithMethod:@"POST" path:path parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 在此位置生成一个要上传的数据体
        // form对应的是html文件中的表单
        
        // 在网络开发中，上传文件时，使文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        // 设置时间格式
//        formatter.dateFormat = @"yyyyMMddHHmmss";
//        NSString *str = [formatter stringFromDate:[NSDate date]];
//        NSString *fileName = [NSString stringWithFormat:@"%@.%@", str, dataType];
        /*
         此方法参数
         1. 要上传的[二进制数据]
         2. 对应网站上处理文件的[字段"file"]
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
//        for (NSString *key in dataDic.allKeys) {
//            [formData appendPartWithFileData:[dataDic objectForKey:key] name:key fileName:fileName mimeType:dataType];
//        }
//    }];
//    
//    AFHTTPRequestOperation *operation = [self.client HTTPRequestOperationWithRequest:request success:success failure:failure];
//    [self.client enqueueHTTPRequestOperation:operation];
}

//获取加密字符串
+ (NSString *)encryptionJsonEncodeStringFrom:(NSDictionary *)paramsDic
{
    NSString *encryptionJsonStr = [JsonString jsonStringWithDictionary:paramsDic];//@"{\"tel\":\"收到个个\",\"type\":\"10\"}";//[JsonString jsonStringWithDictionary:paramsDic];
    return [JoDes encode:encryptionJsonStr key:EncryKeyString];
//    return [DesEncrypt encryptUseDES:encryptionJsonStr key:EncryKeyString];
}

//解密字符串为字符串
+ (NSString *)getDecodeStringFrom:(NSString *)string {
    return [JoDes decode:string key:EncryKeyString];
}

//解密字符串为字典
+ (NSDictionary *)getDecodeDictionaryFrom:(NSString *)string {
    NSString *decryptionStr = [JoDes decode:string key:EncryKeyString];
//    [DesEncrypt decryptUseDES:string key:EncryKeyString];
    return [TCUtils dictionaryFromJson:decryptionStr];
}

//请求方法。加密向接口请求数据，并接收返回值。path方法路径；parameters参数；success请求成功时处理方法；failure请求失败时处理方法
- (void)EncryptionpostPath:(NSString *)path
                parameters:(NSDictionary *)parameters
                   success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))successEnc
                   failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failureEnc
{
    
    NSString *encryptionJsonStr = [JsonString jsonStringWithDictionary:parameters];
    //生成加密字典
    NSMutableDictionary *encryptionDic = [[NSMutableDictionary alloc]init];
    [encryptionDic setObject:[JoDes encode:encryptionJsonStr key:EncryKeyString] forKey:@"P"];
    
    [self postPath:path parameters:encryptionDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (successEnc) {
            
            NSString *decryptionStr = [JoDes decode:[[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] key:EncryKeyString];
            NSDictionary *resultDic = [TCUtils dictionaryFromJson:decryptionStr];
            successEnc(operation, resultDic);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failureEnc) {
            failureEnc(operation, error);
        }
    }];
}

//请求方法。加密向接口请求数据，并接收返回值。path方法路径；parameters参数；success请求成功时处理方法；failure请求失败时处理方法
- (void)EncryptionpostPath:(NSString *)path
                parameters:(NSDictionary *)parameters
                 urlEncode:(BOOL)urlEncode
                   success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))successEnc
                   failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failureEnc
{
    
    NSString *encryptionJsonStr = [JsonString jsonStringWithDictionary:parameters];
    //生成加密字典
    NSMutableDictionary *encryptionDic = [[NSMutableDictionary alloc]init];
    [encryptionDic setObject:[JoDes encode:encryptionJsonStr key:EncryKeyString urlEncode:urlEncode] forKey:@"P"];
    
    [self postPath:path parameters:encryptionDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (successEnc) {
            
            NSString *decryptionStr = [JoDes decode:[[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] key:EncryKeyString];
            NSDictionary *resultDic = [TCUtils dictionaryFromJson:decryptionStr];
            successEnc(operation, resultDic);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failureEnc) {
            failureEnc(operation, error);
        }
    }];
}


//请求方法。加密向接口请求数据，并返回未解密的数据。path方法路径；parameters参数；success请求成功时处理方法；failure请求失败时处理方法
- (void)EncryptionpostPath2:(NSString *)path
                 parameters:(NSDictionary *)parameters
                    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))successEnc
                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failureEnc;
{
    
    NSString *encryptionJsonStr = [JsonString jsonStringWithDictionary:parameters];
    //生成加密字典
    NSMutableDictionary *encryptionDic = [[NSMutableDictionary alloc]init];
    [encryptionDic setObject:[JoDes encode:encryptionJsonStr key:EncryKeyString] forKey:@"P"];
    
    [self postPath:path parameters:encryptionDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (successEnc) {
            
//            NSString *decryptionStr = [JoDes decode:[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding] key:EncryKeyString];
//            NSDictionary *resultDic = [TCUtils dictionaryFromJson:decryptionStr];
            successEnc(operation, responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failureEnc) {
            failureEnc(operation, error);
        }
    }];
}



//请求方法。加密向接口请求数据，并接收返回值。path方法路径；parameters参数；dataDic需上传的数据；dataType数据类型；success请求成功时处理方法；failure请求失败时处理方法
- (void)EncryptionpostPath:(NSString *)path
      parameters:(NSDictionary *)parameters
         dataDic:(NSDictionary *)dataDic
        dataType:(NSString *)dataType
         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    //上传请求POST
    
//    NSString *encryptionJsonStr = [JsonString jsonStringWithDictionary:parameters];
//    
//    //生成加密字典
//    NSMutableDictionary *encryptionDic = [[NSMutableDictionary alloc]init];
//    [encryptionDic setObject:[JoDes encode:encryptionJsonStr key:EncryKeyString] forKey:@"P"];
//    
//    NSMutableURLRequest *request = [self.client multipartFormRequestWithMethod:@"POST" path:path parameters:encryptionDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 在此位置生成一个要上传的数据体
        // form对应的是html文件中的表单
        
        // 在网络开发中，上传文件时，使文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        /*
         此方法参数
         1. 要上传的[二进制数据]
         2. 对应网站上处理文件的[字段"file"]
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
//        for (NSString *key in dataDic.allKeys) {
//            [formData appendPartWithFileData:[dataDic objectForKey:key] name:key fileName:fileName mimeType:dataType];
//        }
//    }];
//    
//    AFHTTPRequestOperation *operation = [self.client HTTPRequestOperationWithRequest:request success:success failure:failure];
//    [self.client enqueueHTTPRequestOperation:operation];
}

- (void)webServicePostMethod:(NSString *)method
                  parameters:(NSDictionary *)parameters
                     success:(void (^)(id responseObject))success
                     failure:(void (^)(NSError *error))failure
{
    [self WeatherTest:method parameters:parameters success:^(id responseObject) {
        success(responseObject);
    } failure:^(NSError *error) {
        failure(error);
    }];
    
}

- (void)webServicePostMethod2:(NSString *)method
                  parameters:(NSDictionary *)parameters
                     success:(void (^)(id responseObject))success
                     failure:(void (^)(NSError *error))failure
{
    [self WeatherTest2:method parameters:parameters success:^(id responseObject) {
        success(responseObject);
    } failure:^(NSError *error) {
        failure(error);
    }];
    
}

-(void)WeatherTest:(NSString *)method
        parameters:(NSDictionary *)parameters
           success:(void (^)(id responseObject))success
           failure:(void (^)(NSError *error))failure
{
    NSString *encryptionJsonStr = [JsonString jsonStringWithDictionary:parameters];
    
    //生成加密字典
    NSMutableDictionary *encryptionDic = [[NSMutableDictionary alloc]init];
    [encryptionDic setObject:[JoDes encode:encryptionJsonStr key:EncryKeyString2] forKey:@"plist"];
    
    SoapUtility *soaputility=[[SoapUtility alloc] initFromFile:@"WeatherWebService"];
    NSString *postData=[soaputility BuildSoapwithMethodName:method withParas:encryptionDic];
    
    SoapService *soaprequest=[[SoapService alloc] init];
    soaprequest.PostUrl=@"http://121.40.178.93:8088/2015Robotreference/phdAppJiekou2015.asmx";
    soaprequest.SoapAction=[soaputility GetSoapActionByMethodName:method SoapType:SOAP];
    
    //异步请求
    [soaprequest PostAsync:postData Success:^(NSString *response) {
        DDXMLDocument *doc = [[DDXMLDocument alloc] initWithXMLString:response options:0 error:nil];
        DDXMLElement *xmlElement = [doc rootElement];
        
        while ([xmlElement elementsForName:[NSString stringWithFormat:@"%@Result", method]].count < 1) {
            xmlElement = xmlElement.children[0];
        }
        id array = [xmlElement elementsForName:[NSString stringWithFormat:@"%@Result", method]];
        xmlElement = array[0];
        id resutl = [[xmlElement children][0] stringValue];
        
        NSString *decryptionStr = [JoDes decode:resutl key:EncryKeyString2];
        NSDictionary *resultDic = [TCUtils dictionaryFromJson:decryptionStr];
        success(resultDic);
    } falure:^(NSError *response) {
        id responseid = response;
        failure(responseid);
    }];
}

-(void)WeatherTest2:(NSString *)method
        parameters:(NSDictionary *)parameters
           success:(void (^)(id responseObject))success
           failure:(void (^)(NSError *error))failure
{
    NSString *encryptionJsonStr = [JsonString jsonStringWithDictionary:parameters];
    
    //生成加密字典
    NSMutableDictionary *encryptionDic = [[NSMutableDictionary alloc]init];
    [encryptionDic setObject:[JoDes encode:encryptionJsonStr key:EncryKeyString2] forKey:@"plist"];
    
    SoapUtility *soaputility=[[SoapUtility alloc] initFromFile:@"WeatherWebService"];
    NSString *postData=[soaputility BuildSoapwithMethodName:method withParas:encryptionDic];
    
    SoapService *soaprequest=[[SoapService alloc] init];
    soaprequest.PostUrl=@"http://121.40.178.93:8088/2015Robotreference/phdAppJiekou2015.asmx";
    soaprequest.SoapAction=[soaputility GetSoapActionByMethodName:method SoapType:SOAP];
    
    //异步请求
    [soaprequest PostAsync:postData Success:^(NSString *response) {
        DDXMLDocument *doc = [[DDXMLDocument alloc] initWithXMLString:response options:0 error:nil];
        DDXMLElement *xmlElement = [doc rootElement];
        
        while ([xmlElement elementsForName:[NSString stringWithFormat:@"%@Result", method]].count < 1) {
            xmlElement = xmlElement.children[0];
        }
        id array = [xmlElement elementsForName:[NSString stringWithFormat:@"%@Result", method]];
        xmlElement = array[0];
        id resutl = [[xmlElement children][0] stringValue];
        
        NSString *decryptionStr = [JoDes decode:resutl key:EncryKeyString2];
//        NSDictionary *resultDic = [TCUtils dictionaryFromJson:decryptionStr];
        success(decryptionStr);
    } falure:^(NSError *response) {
        id responseid = response;
        failure(responseid);
    }];
}

/**
 *  @author Jakey
 *
 *  @brief  下载文件
 *
 *  @param paramDic   附加post参数
 *  @param requestURL 请求地址
 *  @param savedPath  保存 在磁盘的位置
 *  @param success    下载成功回调
 *  @param failure    下载失败回调
 *  @param progress   实时下载进度回调
 */
- (void)downloadFileWithOption:(NSDictionary *)paramDic
                 withInferface:(NSString*)requestURL
                     savedPath:(NSString*)savedPath
               downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
               downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                      progress:(void (^)(float progress))progress

{
    
    //沙盒路径    //NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxx.zip"];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request =[serializer requestWithMethod:@"POST" URLString:requestURL parameters:paramDic error:nil];
    
    //以下是手动创建request方法 AFQueryStringFromParametersWithEncoding有时候会保存
    //    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]];
    //   NSMutableURLRequest *request =[[[AFHTTPRequestOperationManager manager]requestSerializer]requestWithMethod:@"POST" URLString:requestURL parameters:paramaterDic error:nil];
    //
    //    NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    //
    //    [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
    //    [request setHTTPMethod:@"POST"];
    //
    //    [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(paramaterDic, NSASCIIStringEncoding) dataUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float p = (float)totalBytesRead / totalBytesExpectedToRead;
        progress(p);
        NSLog(@"download：%f", (float)totalBytesRead / totalBytesExpectedToRead);
        
    }];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation,responseObject);
        NSLog(@"下载成功");
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        success(operation,error);
        
        NSLog(@"下载失败");
        
    }];
    
    [operation start];
    
}


////请求方法。向接口请求数据，并接收返回值。path方法路径；parameters参数；success请求成功时处理方法；failure请求失败时处理方法....
//- (void)postPath:(NSString *)path
//      parameters:(NSDictionary *)parameters
//         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
//         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
//{
//    
//    NSURLRequest *request = [self.client requestWithMethod:@"POST" path:path parameters:parameters];
//    AFHTTPRequestOperation *operation = [self.client HTTPRequestOperationWithRequest:request success:success failure:failure];
//    [self.client enqueueHTTPRequestOperation:operation];
//}

@end